#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;

const int gdefaultfd = -1;
#define NUM 4096

class PollServer
{
public:
    PollServer(uint16_t port)
        : _port(port), _listen_fd(std::make_unique<TcpSocket>()), _isrunning(false)
    {
    }
    void Init()
    {
        _listen_fd->BuildTcpSocketMethod(_port);
        for (int i = 0; i < NUM; i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listen_fd->Fd();
        _fds[0].events |= POLLIN;
        //_fds[0].revents由poll来填充
    }
    void Loop()
    {
        // poll如果时间为-1则是阻塞式等待,为0则式非阻塞,>0为超时返回
        int timeout = -1;
        _isrunning = true;
        while (_isrunning)
        {
            int n = poll(_fds, NUM, timeout);
            switch (n)
            {
            case -1:
            {
                perror("poll");
                break;
            }
            case 0:
            {
                std::cout << "timeout..." << std::endl;
                break;
            }
            default: // 有消息了,分发给对应模块进行处理
            {
                std::cout << "有事件就绪了" << std::endl;
                Dispatcher();
                break;
            }
            }
        }
    }
    void Dispatcher()
    {
        for (int i = 0; i < NUM; i++)
        {
            if (_fds[i].fd == gdefaultfd) // 跳过非法文件描述符
            {
                continue;
            }
            if (_fds[i].fd == _listen_fd->Fd()) // 监听文件描述符
            {
                if (_fds[i].revents & POLLIN) // 检测监听文件描述符对应的事件是否就绪
                {
                    Accept();
                }
            }
            else // IO文件描述符
            {
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);
                }
            }
        }
    }
    void Accept()
    {
        InetAddr client;
        int newsockfd = _listen_fd->Accepter(&client);
        if (newsockfd < 0)
        {
            perror("accept");
        }
        // 将建立的文件描述符交给poll进行管理
        else
        {
            std::cout << "接受了一个新链接,sockfd: " << newsockfd << std::endl;
            int pos = -1;
            for (int i = 0; i < NUM; i++)
            {
                if (_fds[i].fd == gdefaultfd)
                {
                    pos = i;
                    break;
                }
            }
            if (pos == -1) // 服务器满了
            {
                std::cout << "服务器已经满了" << std::endl;
                close(newsockfd);
            }
            else
            {
                _fds[pos].fd = newsockfd;
                _fds[pos].events = POLLIN;
                // 这句话和_fds[pos].events |= POLLIN;的区别就在于是否要清空原先设计的标志位
            }
        }
    }
    void Recver(int who)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[who].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " << buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(Loglevel::DEBUG) << "客户端退出, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = 0;
            _fds[who].revents = 0;
        }
        else
        {
            LOG(Loglevel::ERROR) << "客户端读取出错, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = 0;
            _fds[who].revents = 0;
        }
    }
    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_fd;
    bool _isrunning;
    struct pollfd _fds[NUM];
};